package team

import (
	"sanguo/node/common/transaction"
	"sanguo/node/node_team"

	ss_rpc "sanguo/protocol/ss/rpc"
	"sanguo/rpc/leaveTeam"
	"sanguo/rpc/teamToGameMsg"

	"github.com/golang/protobuf/proto"
)

type LeaveTeam struct {
}

func (this *LeaveTeam) OnCall(replyer *leaveTeam.LeaveTeamReplyer, arg *ss_rpc.LeaveTeamReq) {

	_team := TeamMgr.GetTeam(arg.GetTeamID())

	resp := &ss_rpc.LeaveTeamResp{
		Ok: proto.Int32(0),
	}
	if _team == nil {
		node_team.Debugln("LeaveTeam no team")
		replyer.Reply(resp)
	} else {
		_role := _team.GetRole(arg.GetRoleID())
		if _role != nil {

			_team.DelRole(_role.RoleID)
			resp.Ok = proto.Int32(1)
			replyer.Reply(resp)

			//队伍成员为空 则解散队伍
			//如果队长离开 找一位队员成为新队长

			if _team.GetRoleCount() == 0 {
				TeamMgr.DelTeam(_team.TeamID)
			} else {
				if _role.RoleID == _team.Header {
					//设置新的队长
					newHeader := _team.GetFirstRole()

					_team.Header = newHeader.RoleID
					_team.ApplyRoles = map[uint64]*ApplyRole{}

					toGame := &ss_rpc.TeamToGameMsgReq{
						MsgType:  ss_rpc.TTGType(ss_rpc.TTGType_Team_Header).Enum(),
						RoleID:   proto.Uint64(newHeader.RoleID),
						UserID:   proto.String(newHeader.UserID),
						HeaderID: proto.Uint64(newHeader.RoleID),
					}
					teamToGameMsg.AsynCall(newHeader.Game, toGame, transaction.TransTimeoutMs, func(respMsg *ss_rpc.TeamToGameMsgResp, err error) {
						if nil == err && respMsg.GetOk() == 1 {
							UpdateTeamToClients(_team)
						}
					})

				} else {
					UpdateTeamToClients(_team)
				}
			}
		} else {
			node_team.Debugln("LeaveTeam fail: _role is nil")
			resp.Ok = proto.Int32(1)
			replyer.Reply(resp)
		}
	}

}

func init() {
	leaveTeam.Register(&LeaveTeam{})
}
